package com.kingdee.openimport.patch_service.service.impl;

import com.kingdee.openimport.patch_service.service.IRedisCacheService;
import com.kingdee.openimport.patch_service.util.StringUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Niki on 2018/5/9 14:24
 */
@Service
public class RedisCacheServiceImpl implements IRedisCacheService {
    @Resource
    JedisSentinelPool pool;

    /* 最新补丁版本 */
    private static final String LATEST_VERSION = "EAS:PATCH:VERSION_LATEST";

    /* 已存在的补丁版本 */
    private static final String EXIT_VERSION_SET = "EAS:PATCH:VERSION_EXIT";


    @Override
    public void setLatesVersion(String version) {
        Jedis jedis = pool.getResource();
        try {
            jedis.set(LATEST_VERSION, version);
        } finally {
            jedis.close();
        }
    }

    @Override
    public String getLatestVersion() {
        Jedis jedis = pool.getResource();
        try {
            if (jedis.exists(LATEST_VERSION)) {
                return jedis.get(LATEST_VERSION);
            }
        } finally {
            jedis.close();
        }
        return null;
    }

    @Override
    public void addExistVersion(String version) {
        Jedis jedis = pool.getResource();
        try {
            jedis.sadd(EXIT_VERSION_SET, version);
        } finally {
            jedis.close();
        }
    }

    @Override
    public Set<String> getExitVersion() {
        Jedis jedis = pool.getResource();
        try {
            if (jedis.exists(EXIT_VERSION_SET)) {
                return jedis.sinter(EXIT_VERSION_SET);
            }
        } finally {
            jedis.close();
        }
        return new HashSet<>();
    }

    @Override
    public boolean versionInExist(String version) {
        if (StringUtils.isBlank(version)) {
            return false;
        }
        Jedis jedis = pool.getResource();
        try {
            return jedis.sismember(EXIT_VERSION_SET, version);
        } finally {
            jedis.close();
        }
    }
}
